package cn.wolfcode.producer._02_sendway;

import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.CountDownLatch;

/**
 * 异步消息发送
 */
public class AsyncProducter {
    //同步发送消息
    public static void main(String[] args) throws Exception {
        //1.创建一个生产者对象
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer("api-producer-demo");
        //2.设置名字服务的地址
        defaultMQProducer.setNamesrvAddr("127.0.0.1:9876");
        //3.启动生产者
        defaultMQProducer.start();
        //设置发送时间，防止发送超时
        defaultMQProducer.setSendMsgTimeout(10000);
        //记录发送次数
        CountDownLatch count = new CountDownLatch(100);
        //4.创建一个消息
        for (int i = 0; i < 100; i++) {
            Message message = new Message("03-sendway-boot", "TagA", "你好，rocketMQ！".getBytes());
            //5.生产者发送异步消息
            defaultMQProducer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    count.countDown();//次数 - 1
                    System.out.println("消息发送成功");
                    System.out.println(JSON.toJSONString(sendResult));
                }

                @Override
                public void onException(Throwable e) {
                    count.countDown();
                    System.out.println("消息发送失败"+e.getMessage());
                    System.out.println("处理失败消息");
                }
            });
        }
        count.await();//异步发送消息，生产者必须保持状态，否则报错
        //6.关闭连接
        defaultMQProducer.shutdown();
    }
}
